package org.linlinjava.litemall.wx.service;

import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.wx.constant.LitemallWXConstants;
import org.linlinjava.litemall.wx.util.RewardsUtils;
import org.linlinjava.litemall.wx.vo.WxRewardDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static org.linlinjava.litemall.wx.util.WxResponseCode.INVITE_CODE_ERROR;
import static org.linlinjava.litemall.wx.util.WxResponseCode.MOBILE_CODE_ONE;

/**
 * wx奖励服务
 *
 * @author yliyun
 * @program: litemall
 * @description: 分销
 * @author: chenyu
 * @create: 2022-03-18 19:09
 * @date 2022/09/20
 */
@Service
@RequiredArgsConstructor
public class WxRewardService {
  private final LitemallDistributionLogService litemallDistributionLogService;
  private final LitemallDistributionDetailService litemallDistributionDetailService;
  private final LitemallUserService userService;
  private final NotifyService notifyService;
  private final LumiereCouponStrategyService lumiereCouponStrategyService;
  private final LumiereCouponService lumiereCouponService;
  private final RewardsUtils rewardsUtils;

  /**
   * 奖励细节
   *
   * @param userId 用户id
   * @return {@link Object}
   */
  public Object rewardDetail(Integer userId) {
    List<LitemallDistributionLog> logs = litemallDistributionLogService.logsByUserId(userId);
    List<LitemallDistributionDetail> detailList = new ArrayList<>();

    logs.stream().forEach(log -> {
      List<LitemallDistributionDetail> details = litemallDistributionDetailService.listByLogId(log.getId());
      detailList.addAll(details);
    });
    List<WxRewardDetailVo> vos = new ArrayList<>();

      detailList.stream().forEach(detail -> {
      WxRewardDetailVo vo = new WxRewardDetailVo();
        /**
         * TODO 这里排除当前用户作为被邀请人的记录，后续修改
         */
      if (detail.getRegisterId() != null && detail.getRegisterId().intValue() != userId) {
        LitemallUser user = userService.findById(detail.getRegisterId());
        if(user != null){
          vo.setRegisteDate(detail.getAddTime().toLocalDate().toString());
          vo.setAvaliableAmount(user.getAvailableAmount());

          List<String> couponNames = new ArrayList<>();

          //赠送福利：优惠券和积分
          if( detail.getPresentCouponId().length > 0){
            for (int i = 0; i < detail.getPresentCouponId().length; i++) {
              LumiereCouponStrategy couponStrategy =  lumiereCouponStrategyService.findByid(detail.getPresentCouponId()[i]);
              LumiereCoupon coupon = lumiereCouponService.getById(couponStrategy.getCouponId());
              couponNames.add(coupon.getName());
            }
          }
          vo.setCouponNames(couponNames);
          vo.setPoints(detail.getPresentPoints());
          vo.setUserId(user.getId());
          vo.setUserName(user.getUsername());
          vos.add(vo);
        }
      }

    });
    return ResponseUtil.okList(vos);

  }

  /**
   * 发送电子邮件
   *
   * @param userId 用户id
   * @param email  电子邮件
   * @return {@link Object}
   */
  public Object sendEmail(Integer userId,String email){
     LitemallUser user = userService.findById(userId);
     if(ObjectUtil.isNull(user) || user.getInvitedCode() == null){
       return ResponseUtil.fail(INVITE_CODE_ERROR,"用户不存在或者无邀请码");
     }
     //发送邮箱通知
     notifyService.notifyMail(String.format(LitemallWXConstants.WX_INVITATION_USER_REGISTER_TITLE_EMAIL,user.getNickname()),
            String.format(LitemallWXConstants.WX_INVITATION_USER_REGISTER_EMAIL,user.getNickname(),user.getInvitedCode()),email);
     //发放奖励
     rewardsUtils.getRewardInvitation(user,email);
     return ResponseUtil.ok("发送成功");
  }

  /**
   * 发送手机
   *
   * @param userId 用户id
   * @param mobile 移动
   * @return {@link Object}
   */
  public Object sendMobile(Integer userId,String mobile){
    LitemallUser user = userService.findById(userId);
    if(ObjectUtil.isNull(user) || user.getInvitedCode() == null){
      return ResponseUtil.fail(INVITE_CODE_ERROR,"用户不存在或者无邀请码");
    }
    //发送短信通知
    notifyService.notifySmsTemplate(MOBILE_CODE_ONE+mobile, NotifyType.INVITE, new String[]{user.getInvitedCode()});
    //发放奖励
    rewardsUtils.getRewardInvitation(user,mobile);
    return ResponseUtil.ok("发送成功");
  }
}
